<script setup lang="ts">
defineOptions({
  name: "ALL_FAB_PROVISION_CRAFT_RELEVANCY"
});
import { ref, reactive, computed, watch, ComputedRef, getCurrentInstance } from "vue";
import { PxMessageBox } from "px-ui";
import { useRoute } from "vue-router";
import { useRouterStoreHook } from "@/store/modules/router";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import ReTeleport from "@/components/ReTeleport";
import search from "../components/search.vue";
import relevancyTable from "./components/relevancyTable.vue";
import { getFabTechnologySelectOptions, getFabProductSelectOptions, getFabLotSelectOptions, getFabWaferSelectOptions } from "@/api/modules/fab";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

const { proxy }: any = getCurrentInstance();

const route = useRoute();
const routerStore = useRouterStoreHook();

const tableParams = ref<Record<string, any>>({});
const searchOption: ComputedRef<Array<CommonSearch.SearchOption>> = computed(() => {
  const {
    query: { params = "" }
  } = route;
  const query = JSON.parse(decodeURI(params as string));
  let technology = "";
  let product = "";
  let lot = "";
  let wafer = "";
  if (query) {
    const { technology: technology_ = "", product: product_ = "", lot: lot_ = "", wafer: wafer_ = "" } = query;
    technology = technology_;
    product = product_;
    lot = lot_;
    wafer = wafer_;
  }
  return [
    {
      label: "工艺选择",
      key: "technology",
      value: "",
      defaultValue: technology,
      // 调试
      // value: "28nm",
      type: "select",
      axiosApi: getFabTechnologySelectOptions,
      mapOption: ({ name: label = null, code: value = null }) => ({ label, value }),
      placeholder: "请选择工艺"
    },
    {
      label: "产品选择",
      key: "product",
      value: "",
      defaultValue: product,
      // 调试
      // value: "SOC28",
      type: "select",
      axiosApi: getFabProductSelectOptions,
      mapOption: ({ name: label = null, code: value = null }) => ({ label, value }),
      placeholder: "请选择产品"
    },
    {
      label: "Lot编号",
      key: "lot",
      value: "",
      defaultValue: lot,
      // 调试
      // value: "YPP001393",
      type: "select",
      remote: true,
      selectRemoteApi: getFabLotSelectOptions,
      getParams: (lotName: string) => ({ lotName }),
      mapOption: ({ name: label = null, code: value = null }) => ({ label, value }),
      placeholder: "请输入Lot编号"
    },
    {
      label: "Wafer编号",
      key: "wafer",
      value: "",
      defaultValue: wafer,
      // 调试
      // value: "",
      type: "select",
      remote: true,
      selectRemoteApi: getFabWaferSelectOptions,
      getParams: (waferName: string) => ({ waferName }),
      mapOption: ({ name: label = null, code: value = null }) => ({ label, value }),
      props: {
        clearable: false
      },
      placeholder: "请输入Wafer编号"
    }
  ];
});

let defaultParams: Record<string, string> = {
  className: "",
  layerId: "",
  routeId: ""
};
let leftCurrentParams: any = {};
let rightCurrentParams: any = {};

const defaultSearchParams = reactive<{ period: string; startTime: string; endTime: string; parameter: string }>({
  period: "week",
  startTime: "",
  endTime: "",
  parameter: ""
});

/**
 * @description:  search change 事件
 * @param {*} params  搜索条件参数
 * @param {*} types   数据选择
 * @param {*} flag    是否首次触发
 * @param {*} flag2   是否物料数据改变
 * @param {*} flag3   是否从全不选到选择
 * @return {*}
 */
const searchChangeHandler = async (
  params: Record<string, any>,
  types: Array<string>,
  flag: boolean = false,
  flag2: boolean = false,
  flag3: boolean = false
) => {
  leftCurrentParams = { ...leftCurrentParams, ...params };
  !flag && updateParams();
};

const updateParams = () => {
  tableParams.value = { ...defaultParams, ...leftCurrentParams, ...rightCurrentParams };
};

const submitSearchFormHandler = (form: any, flag: boolean = false) => {
  rightCurrentParams = { ...rightCurrentParams, ...form };
  !flag && updateParams();
};

const resetSearchFormHandler = (form: any) => {
  rightCurrentParams = { ...rightCurrentParams, ...form };
  updateParams();
};

const exportHandler = useThrottleFn(() => {
  const url = "/fab/api/v1/supplyConsume/technologyAndEqp/export";
  const params = { ...tableParams.value };
  proxy.download("post", url, params);
  PxMessageBox.alert("正在导出数据，数据处理可能需要一定时间，请耐心等待，数据准备完毕将直接下载。", "导出", {
    confirmButtonText: "我知道了"
  });
}, delay);

watch(
  () => route.query,
  val => {
    const {
      query: { params = "" }
    } = route;
    const query = JSON.parse(decodeURI(params as string));
    if (query) {
      const className = routerStore.getSubject === "ALL" ? "" : routerStore.getSubject;
      const {
        startTime = "",
        endTime = "",
        parameter = "",
        layerId = "",
        routeId = "",
        technology = "",
        product = "",
        lot = "",
        wafer = "",
        period = ""
      } = query;
      defaultSearchParams.period = (period as string) || "week";
      defaultSearchParams.startTime = startTime as string;
      defaultSearchParams.endTime = endTime as string;
      defaultSearchParams.parameter = parameter as string;
      defaultParams = { ...defaultParams, className, layerId, routeId };
      leftCurrentParams = { ...leftCurrentParams, startTime, endTime, parameter };
      rightCurrentParams = { ...rightCurrentParams, technology, product, lot, wafer };
      updateParams();
    }
  },
  {
    immediate: true,
    deep: true,
    once: true
  }
);
</script>

<template>
  <div class="craft-relevancy">
    <ReTeleport placement="left" :width="182">
      <div class="provision-area-search">
        <search
          ref="searchRef"
          type="area"
          dataTypesDisabled
          v-model:period="defaultSearchParams.period"
          :startTime="defaultSearchParams.startTime"
          :endTime="defaultSearchParams.endTime"
          :parameter="defaultSearchParams.parameter"
          @change="searchChangeHandler"
        />
      </div>
    </ReTeleport>
    <div class="craft-relevancy-content">
      <div class="craft-relevancy-search">
        <commonSearch
          v-if="searchOption?.length"
          ref="commonSearchRef"
          :row-num="4"
          :option="searchOption"
          :operationSpan="3"
          @submit="submitSearchFormHandler"
          @reset="resetSearchFormHandler"
        />
      </div>
      <px-button v-has="'ALL_FAB_PROVISION_CRAFT_RELEVANCY_EXPORT_BTN'" type="primary" plain @click="exportHandler">报表导出</px-button>
      <div class="craft-relevancy-table">
        <relevancyTable :params="tableParams" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" global>
.provision-area-search {
  box-sizing: border-box;
  width: 100%;
  padding: 0 16px 16px;
}
</style>

<style lang="scss" scoped>
.craft-relevancy {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 16px;
  overflow: auto;
  background-color: #fff;

  .craft-relevancy-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
    width: 100%;
    height: 100%;

    .craft-relevancy-search {
      width: 100%;
    }

    .px-button {
      width: fit-content;
    }

    .craft-relevancy-table {
      flex: 1;
      width: 100%;
    }
  }
}
</style>
